<template>
  <div class="api-test-container">
    <h2>API接口可用性测试</h2>
    
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <span>测试产品明细相关API接口</span>
        </div>
      </template>
      
      <div class="test-form">
        <el-form :model="testForm" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入库单号">
                <el-input v-model="testForm.entryOrderNumber" placeholder="请输入入库单号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品ID">
                <el-input-number v-model="testForm.productId" :min="1" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        
        <div class="test-buttons">
          <el-button type="primary" @click="testGetAllProductDetails" :loading="loading.getAll">
            测试获取所有产品明细
          </el-button>
          <el-button type="success" @click="testGetProductDetailsByOrder" :loading="loading.getByOrder">
            测试根据入库单号获取明细
          </el-button>
          <el-button type="warning" @click="testAddProductDetail" :loading="loading.add">
            测试新增产品明细
          </el-button>
          <el-button type="info" @click="testUpdateProductDetail" :loading="loading.update">
            测试更新产品明细
          </el-button>
        </div>
      </div>
      
      <div class="test-results">
        <h3>测试结果：</h3>
        <el-input
          v-model="testResult"
          type="textarea"
          :rows="20"
          placeholder="测试结果将显示在这里..."
          readonly
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { MES_LXK_ApiHost } from '@/utils/Interceptors'

const testResult = ref('')
const loading = reactive({
  getAll: false,
  getByOrder: false,
  add: false,
  update: false
})

// 测试表单数据
const testForm = reactive({
  entryOrderNumber: 'RK20250821135836262',
  productId: 1,
  productName: '测试产品',
  productNumber: 'P000001',
  productSpecification: '测试规格',
  inventoryUnit: '个',
  inventoryQuantity: 10,
  current: 100,
  maxInventory: 1000,
  minInventory: 100,
  safetyInventory: 200
})

const logResult = (title: string, result: any) => {
  const timestamp = new Date().toLocaleString()
  const resultStr = JSON.stringify(result, null, 2)
  testResult.value = `[${timestamp}] ${title}:\n${resultStr}\n\n${testResult.value}`
}

// 测试获取所有产品明细
const testGetAllProductDetails = async () => {
  loading.getAll = true
  try {
    logResult('开始测试获取所有产品明细', '')
    
    const possiblePaths = [
      '/api/ProductDetail/GetAll',
      '/api/InboundOrderDetail/GetAll',
      '/api/ProductDetail',
      '/api/InboundOrderDetail'
    ]
    
    for (const path of possiblePaths) {
      try {
        logResult(`尝试API路径: ${path}`, '')
        const response = await MES_LXK_ApiHost.get(path)
        logResult(`✅ API调用成功: ${path}`, response.data)
        ElMessage.success(`获取所有产品明细成功: ${path}`)
        return
      } catch (error: any) {
        logResult(`❌ API调用失败: ${path}`, {
          status: error.response?.status,
          message: error.message,
          data: error.response?.data
        })
      }
    }
    
    ElMessage.error('所有获取所有产品明细的API都失败了')
  } catch (error: any) {
    logResult('测试失败', error)
    ElMessage.error('测试失败')
  } finally {
    loading.getAll = false
  }
}

// 测试根据入库单号获取明细
const testGetProductDetailsByOrder = async () => {
  loading.getByOrder = true
  try {
    logResult('开始测试根据入库单号获取明细', testForm.entryOrderNumber)
    
    const possiblePaths = [
      `/api/InboundOrder/GetProductDetails/${testForm.entryOrderNumber}`,
      `/api/ProductDetail/GetAll?entryOrderNumber=${testForm.entryOrderNumber}`,
      `/api/ProductDetail/GetByOrderNumber/${testForm.entryOrderNumber}`,
      `/api/ProductDetail/GetDetails/${testForm.entryOrderNumber}`,
      `/api/ProductDetail?entryOrderNumber=${testForm.entryOrderNumber}`,
      `/api/InboundOrderDetail?entryOrderNumber=${testForm.entryOrderNumber}`
    ]
    
    for (const path of possiblePaths) {
      try {
        logResult(`尝试API路径: ${path}`, '')
        const response = await MES_LXK_ApiHost.get(path)
        logResult(`✅ API调用成功: ${path}`, response.data)
        ElMessage.success(`根据入库单号获取明细成功: ${path}`)
        return
      } catch (error: any) {
        logResult(`❌ API调用失败: ${path}`, {
          status: error.response?.status,
          message: error.message,
          data: error.response?.data
        })
      }
    }
    
    ElMessage.error('所有根据入库单号获取明细的API都失败了')
  } catch (error: any) {
    logResult('测试失败', error)
    ElMessage.error('测试失败')
  } finally {
    loading.getByOrder = false
  }
}

// 测试新增产品明细
const testAddProductDetail = async () => {
  loading.add = true
  try {
    const payload = {
      entryOrderNumber: testForm.entryOrderNumber,
      EntryOrderNumber: testForm.entryOrderNumber,
      productId: testForm.productId,
      productName: testForm.productName,
      productNumber: testForm.productNumber,
      productSpecification: testForm.productSpecification,
      inventoryUnit: testForm.inventoryUnit,
      maxInventory: testForm.maxInventory,
      minInventory: testForm.minInventory,
      safetyInventory: testForm.safetyInventory,
      current: testForm.current,
      inventoryQuantity: testForm.inventoryQuantity,
      num: testForm.inventoryQuantity,
      isDelete: false,
      createdBy: 'test',
      modifiedBy: 'test',
      createdTime: new Date().toISOString(),
      modifiedTime: new Date().toISOString()
    }
    
    logResult('开始测试新增产品明细', payload)
    
    const possiblePaths = [
      '/api/ProductDetail/Add',
      '/api/ProductDetail/AddProductDetail',
      '/api/InboundOrderDetail/Add'
    ]
    
    for (const path of possiblePaths) {
      try {
        logResult(`尝试API路径: ${path}`, '')
        const response = await MES_LXK_ApiHost.post(path, payload)
        logResult(`✅ API调用成功: ${path}`, response.data)
        ElMessage.success(`新增产品明细成功: ${path}`)
        return
      } catch (error: any) {
        logResult(`❌ API调用失败: ${path}`, {
          status: error.response?.status,
          message: error.message,
          data: error.response?.data
        })
      }
    }
    
    ElMessage.error('所有新增产品明细的API都失败了')
  } catch (error: any) {
    logResult('测试失败', error)
    ElMessage.error('测试失败')
  } finally {
    loading.add = false
  }
}

// 测试更新产品明细
const testUpdateProductDetail = async () => {
  loading.update = true
  try {
    const payload = {
      id: 1, // 假设ID为1
      entryOrderNumber: testForm.entryOrderNumber,
      EntryOrderNumber: testForm.entryOrderNumber,
      productId: testForm.productId,
      productName: testForm.productName,
      productNumber: testForm.productNumber,
      productSpecification: testForm.productSpecification,
      inventoryUnit: testForm.inventoryUnit,
      maxInventory: testForm.maxInventory,
      minInventory: testForm.minInventory,
      safetyInventory: testForm.safetyInventory,
      current: testForm.current,
      inventoryQuantity: testForm.inventoryQuantity,
      num: testForm.inventoryQuantity,
      isDelete: false,
      createdBy: 'test',
      modifiedBy: 'test',
      createdTime: new Date().toISOString(),
      modifiedTime: new Date().toISOString()
    }
    
    logResult('开始测试更新产品明细', payload)
    
    const possiblePaths = [
      '/api/ProductDetail/Update',
      '/api/InboundOrderDetail/Update',
      '/api/ProductDetail/UpdateDetail'
    ]
    
    for (const path of possiblePaths) {
      try {
        logResult(`尝试API路径: ${path}`, '')
        const response = await MES_LXK_ApiHost.put(path, payload)
        logResult(`✅ API调用成功: ${path}`, response.data)
        ElMessage.success(`更新产品明细成功: ${path}`)
        return
      } catch (error: any) {
        logResult(`❌ API调用失败: ${path}`, {
          status: error.response?.status,
          message: error.message,
          data: error.response?.data
        })
      }
    }
    
    ElMessage.error('所有更新产品明细的API都失败了')
  } catch (error: any) {
    logResult('测试失败', error)
    ElMessage.error('测试失败')
  } finally {
    loading.update = false
  }
}
</script>

<style scoped>
.api-test-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.test-form {
  margin-bottom: 20px;
}

.test-buttons {
  display: flex;
  gap: 12px;
  margin-top: 20px;
  flex-wrap: wrap;
}

.test-results {
  margin-top: 20px;
}

.test-results h3 {
  margin-bottom: 12px;
  color: #303133;
}
</style>

